﻿using System;
using System.Windows.Forms;
using Component;
using Xiaozhou.Plugins;

namespace DynamicPlugInsApp
{
    public partial class Form1 : Form
    {
        private PluginsManager manager = null;
        public Form1()
        {
            InitializeComponent();
            manager = PluginsManager.GetInstance();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            manager.pluginsManagerEvent += EventHandler;
            manager.Run();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (listView1.Items.Count == 0)
                return;


            string pluginName = listView1.SelectedItems[0].Text;
            if (!String.IsNullOrEmpty(pluginName))
            {
                IComponent obj = manager.GetPluginByName(pluginName) as IComponent;

                if (obj != null)
                {
                    MessageBox.Show(obj.Invoke());
                }

            }

        }

        private void EventHandler(PluginEventArgs args)
        {
            MessageBox.Show("Event Type: " + args.EventType.ToString() + Environment.NewLine + args.EventMessage);
            RefreshPlugins();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            RefreshPlugins();
        }

        private void RefreshPlugins()
        {
            listView1.Items.Clear();

            var names = manager.GetPluginNames();

            foreach (var n in names)
            {
                listView1.Items.Add(n);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (listView1.Items.Count == 0)
                return;

            manager.UnloadPluginByName(listView1.SelectedItems[0].Text);
        }
    }
}